package client.comm.baoding.ui

import android.content.Intent
import android.graphics.Color
import android.text.Layout
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import client.comm.baoding.BaseMiddleActivity
import client.comm.baoding.R
import client.comm.baoding.alipay.AlipayUtils
import client.comm.baoding.api.bean.*
import client.comm.baoding.databinding.ActivityConfirmorderBinding
import client.comm.baoding.databinding.LayoutConfirmenterorderitemBinding
import client.comm.baoding.dialog.SelectPayTypeDialog
import client.comm.baoding.ui.vm.ConfirmOrderModel
import client.comm.baoding.utils.TextTool
import client.comm.commlib.dialog.ValidatePwdDialog
import client.comm.commlib.toast.toast
import client.comm.commlib.utils.StoreUtil
import client.comm.commlib.widget.EmptyLayout
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.math.BigDecimal
import java.util.*

class ConfirmOrderActivity :
    BaseMiddleActivity<ConfirmOrderModel, ActivityConfirmorderBinding>() {

    var tradeNo: String = "" //订单编号

    override fun getLayout(): Int {
        return R.layout.activity_confirmorder
    }

    override fun initView() {
        EventBus.getDefault().register(this)
        binding?.apply {
            event = this@ConfirmOrderActivity
            vm = viewModel
            emptyLayout.setOnClickListener {
                viewModel.userInfo()
            }
        }
    }

    override fun observerUI() {
        viewModel.userRet.observe(this, {

            it?.let {
                if (it.isSuccess) {

                    binding.emptyLayout.visibility = View.GONE
                    binding.user = it.data
                    viewModel.payTypeTxt.value = "佣金支付(佣金:${it.data!!.income})"
//                    viewModel.payType.value = 1

                    it.data?.address_list?.let {
                        if (it.size > 0)
                            binding.addr = it[0]
                    }
                } else {
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
                }
            }
        })

        viewModel.commitRet.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    if (viewModel.payType.value == 3) {//支付宝支付
                        tradeNo = it.data!!.trade_no
                        AlipayUtils(this).pay(it.data!!.pay_url)

                    } else {
                        startActivity(Intent(this, GoodsOrderActivity::class.java).apply {
                            putExtra("index", 1)
                        })
                        finish()
                        toast("下单成功")
                    }
                } else {
                    Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
                }
            }
        })
        viewModel.checkOrderPayCall.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    toast("支付成功")
                    finish()
                } else {
                    Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
//                    toast(it.message)
                }
            }
        })

        viewModel.userInfo()
    }

    override fun initViewModel(): ConfirmOrderModel = createViewModel()

    override fun initData() {
        val list = intent.getParcelableArrayListExtra<ShopingBean>("list")
        list?.let {
            binding.goodsWrap.removeAllViews()
            for (data in it) {
                val bindingType =
                    DataBindingUtil.inflate<LayoutConfirmenterorderitemBinding>(
                        LayoutInflater.from(this),
                        R.layout.layout_confirmenterorderitem,
                        binding.goodsWrap,
                        false
                    ).apply {
                        this.bean = data
                        mImgLoader.load(data.goods_img).into(img)

                        commPriceIntegral.apply {
                            var is_price_show: Boolean = false
                            var is_integral_unit_show: Boolean = false

                            if (data.price > 0) {
                                tvPrice.text = "${data.price}"
                                is_price_show = true
                                if (data.integral > 0) {
                                    tvIntegral.text = "+" + data.integral //+ "积分"
                                    is_integral_unit_show = true
                                } else {
                                    tvIntegral.text = ""
                                    is_integral_unit_show = false
                                }

                            } /*else if (data.lpq_price > 0) {
                                TextTool.getBuilder("${data.lpq_price}")
//                                    .setAlign(Layout.Alignment.ALIGN_CENTER)
                                    .setTextSize(18)
                                    .append("体验券").setForegroundColor(Color.parseColor("#000000"))
                                    .setTextSize(12)
                                    .into(tvPrice)
                                is_price_show = true
                                if (data.integral > 0) {
                                    tvIntegral.text = "+" + data.integral //+ "积分"
                                    is_integral_unit_show = true
                                } else {
                                    tvIntegral.text = ""
                                    is_integral_unit_show = false
                                }

                            }*/ else {
                                tvPrice.text = ""
                                is_price_show = false
                                if (data.integral > 0) {
                                    tvIntegral.text = "" + data.integral //+ "积分"
                                    is_integral_unit_show = true
                                } else {
                                    tvIntegral.text = ""
                                    is_integral_unit_show = false
                                }
                            }

                            if (is_price_show) {
                                tvPriceUnit.visibility = View.VISIBLE
                            } else {
                                tvPriceUnit.visibility = View.GONE
                            }

                            if (is_integral_unit_show) {
                                tvIntegralDesc.visibility = View.VISIBLE
                            } else {
                                tvIntegralDesc.visibility = View.GONE
                            }

                            tvPrice.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16F)
                            tvIntegral.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16F)

                            tvPriceUnit.setTextColor(resources!!.getColor(client.comm.commlib.R.color.txt_color))
                            tvPrice.setTextColor(resources!!.getColor(client.comm.commlib.R.color.txt_color))
                            tvIntegral.setTextColor(resources!!.getColor(client.comm.commlib.R.color.txt_color))
                            tvIntegralDesc.setTextColor(resources!!.getColor(client.comm.commlib.R.color.txt_color))
                        }
//                        if (i.price > 0) {
//                            tvPrice.text = "¥${i.price}"
//                            if (i.integral > 0) {
//                                tvIntegral.text = "+" + i.integral + "积分"
//                            } else {
//                                tvIntegral.text = ""
//                            }
//
//                        } else {
//                            tvPrice.text = ""
//                            if (i.integral > 0) {
//                                tvIntegral.text  = "" + i.integral + "积分"
//                            } else {
//                                tvIntegral.text = ""
//                            }
//                        }


                    }
                binding.goodsWrap.addView(bindingType.root)
            }
            updatePrice()
        }
    }

//    var lpq_price_total: Double = 0.0

    fun updatePrice() {
        var number: BigDecimal = BigDecimal(0)
//        var lpq_price_new: BigDecimal = BigDecimal(0)
        var integral: BigDecimal = BigDecimal(0)
//        var integral_f: BigDecimal = BigDecimal(0)
        val items = intent.getParcelableArrayListExtra<ShopingBean>("list")
        items?.let {
            for (b in items) {
                b?.let {
                    number = number.add(BigDecimal(b.num).multiply(BigDecimal(b.price)))
                    /*if (b.lpq_price > 0) {
                        lpq_price_new =
                            lpq_price_new.add(BigDecimal(b.num).multiply(BigDecimal(b.lpq_price)))
                    } else*/

//                    integral_f =
//                        integral_f.add(BigDecimal(b.num).multiply(BigDecimal(b.integral_f)))

                    if (b.integral > 0)
                        integral =
                            integral.add(BigDecimal(b.num).multiply(BigDecimal(b.integral)))
                }
            }
        }
        binding.coupon?.let {
            number = number.subtract(BigDecimal(it.minus_price))
        }

        binding.incGoodsList.apply {
            this.price = "${number.toDouble()}"
            this.integral = "${integral.toDouble()}"

            rlIntegral.visibility = View.VISIBLE

//            lpq_price_total = lpq_price_new.toDouble()
//            tvLpqPrice.text="${integral_f.toDouble()}"
//            TextTool.getBuilder("${lpq_price_new.toDouble()}")
//                .setTextSize(18)
////                .append("体验券").setForegroundColor(Color.parseColor("#000000"))
////                .setTextSize(12)
//                .into(tvLpqPrice)

            /*if (lpq_price_new.toDouble() > 0) {
                rlLpq.visibility = View.VISIBLE
                rlIntegral.visibility = View.GONE
            } else if (integral.toDouble() > 0) {
                rlIntegral.visibility = View.VISIBLE
                rlLpq.visibility = View.GONE
            }*/

            /* else {
                    rlIntegral.visibility = View.GONE
                    rlLpq.visibility = View.GONE
                }*/

        }
        binding.price = "${number.toDouble()}"
        binding.integral = "${integral.toDouble()}"

        binding.commPriceIntegral.apply {
            var is_price_show: Boolean = false
            var is_integral_unit_show: Boolean = false

            var integral = integral.toDouble()
            var price = number.toDouble()
//            var lpqPrice = lpq_price_new.toDouble()
            if (price > 0) {
                tvPrice.text = "${price}"
                is_price_show = true
                if (integral > 0) {
                    tvIntegral.text = "+" + integral //+ "积分"
                    is_integral_unit_show = true
                } else {
                    tvIntegral.text = ""
                    is_integral_unit_show = false
                }
            } /*else if (lpqPrice > 0) {
                TextTool.getBuilder("${lpqPrice}")
                    .setAlign(Layout.Alignment.ALIGN_CENTER).setTextSize(18)
                    .append("体验券").setForegroundColor(Color.parseColor("#E81837"))
                    .setTextSize(12)
                    .into(tvPrice)
                is_price_show = true
                if (integral > 0) {
                    tvIntegral.text = "+" + integral //+ "积分"
                    is_integral_unit_show = true
                } else {
                    tvIntegral.text = ""
                    is_integral_unit_show = false
                }

            }*/ else {
                tvPrice.text = ""
                is_price_show = false
                if (integral > 0) {
                    tvIntegral.text = "" + integral //+ "积分"
                    is_integral_unit_show = true
                } else {
                    tvIntegral.text = ""
                    is_integral_unit_show = false
                }
            }

            if (is_price_show) {
                tvPriceUnit.visibility = View.VISIBLE
            } else {
                tvPriceUnit.visibility = View.GONE
                binding.incGoodsList.rlGoodAccount.visibility = View.GONE
            }

            if (is_integral_unit_show) {
                tvIntegralDesc.visibility = View.VISIBLE
            } else {
                tvIntegralDesc.visibility = View.GONE
            }
        }

        binding.commPriceIntegral1.apply {
            var is_price_show: Boolean = false
            var is_integral_unit_show: Boolean = false

            var integral = integral.toDouble()
            var price = number.toDouble()

//            var lpqPrice = lpq_price_new.toDouble()
//            var integralF= integral_f.toDouble()

            if (price > 0) {
                tvPrice.text = "${price}"
                is_price_show = true
                if (integral > 0) {
                    tvIntegral.text = "+" + integral //+ "积分"
                    is_integral_unit_show = true
                } else {
                    tvIntegral.text = ""
                    is_integral_unit_show = false
                }
            } /*else if (integralF > 0) {
                TextTool.getBuilder("${integralF}")
                    .setAlign(Layout.Alignment.ALIGN_CENTER).setTextSize(18)
                    .append("赠送积分").setForegroundColor(Color.parseColor("#E81837"))
                    .setTextSize(12)
                    .into(tvPrice)
                is_price_show = true
                if (integral > 0) {
                    tvIntegral.text = "+" + integral //+ "积分"
                    is_integral_unit_show = true
                } else {
                    tvIntegral.text = ""
                    is_integral_unit_show = false
                }

            } else {
                tvPrice.text = ""
                is_price_show = false
                if (integral > 0) {
                    tvIntegral.text = "" + integral //+ "积分"
                    is_integral_unit_show = true
                } else {
                    tvIntegral.text = ""
                    is_integral_unit_show = false
                }
            }*/

            if (is_price_show) {
                tvPriceUnit.visibility = View.VISIBLE
            } else {
                tvPriceUnit.visibility = View.GONE
            }

            if (is_integral_unit_show) {
                tvIntegralDesc.visibility = View.VISIBLE
            } else {
                tvIntegralDesc.visibility = View.GONE
            }
        }
//        binding.integral = " 积分${integral.toDouble()}"
//        binding.priceDouble = number.toDouble()
    }

    fun ok() {
        if (binding.addr == null) {
            toast("请选择地址")
            return
        }

        //判断当前商品的体验券佣金
//        if (lpq_price_total > 0) {
//            StoreUtil.getBean<UserInfo>(this)?.let {
//                if (it.income_r <= 0) {
//                    toast("你的体验券不足")
//                    return
//                }
//            }
//        }

//        if (viewModel.payType.value == 0) {
//            toast("请选择支付方式")
//            return
//        }
        selectPayType()

    }

    fun selectAddr() {
        startActivityForResult(Intent(this, AddrMangerActivity::class.java).apply {
            putExtra("select", true)
        }, 0x11)
    }

    fun selectCoupon() {
        startActivityForResult(Intent(this, MeCouponActivity::class.java).apply {
            putExtra("select", true)
            putExtra("price", binding.price!!.toDouble())
        }, 0x12)
    }

    fun selectPayType() {
        SelectPayTypeDialog(this).apply {
//            good_wallet_pin.set(lpq_price_total)//设置体验券佣金

            one = { it, txt ->
                viewModel.payType.value = it
                viewModel.payTypeTxt.value = txt

//                toast("${viewModel.payType.value}")
                val list = intent.getParcelableArrayListExtra<ShopingBean>("list")
                var user_coupons_id = ""
                this@ConfirmOrderActivity.binding.coupon?.let {
                    user_coupons_id = it.user_coupons_id
                }

                if (viewModel.payType.value == 3) {
                    viewModel.commitOrder(
                        list as ArrayList<ShopingBean>,
                        this@ConfirmOrderActivity.binding.addr!!.address_id,
                        user_coupons_id
                    )
                } else {
                    //佣金，分享积分支付时，加一下输入支付密码确认的环节
                    ValidatePwdDialog(this@ConfirmOrderActivity).apply {
                        title = "需要验证支付密码"
                        ok = {
                            viewModel.commitOrderByPayPwdValid(
                                it,
                                list as ArrayList<ShopingBean>,
                                this@ConfirmOrderActivity.binding.addr!!.address_id,
                                user_coupons_id
                            )

                        }

                    }.show()
                }


//                if (viewModel.payType.value == 3) {
//                    viewModel.commitOrder(
//                        list as ArrayList<ShopingBean>,
//                        this@ConfirmOrderActivity.binding.addr!!.address_id,
//                        user_coupons_id
//                    )
//                } else {
//
////                    if(viewModel.payType.value==4){
////                        StoreUtil.getBean<UserInfo>(this@ConfirmOrderActivity)?.let {
////                            if (it.income_r <= 0) {
////                                toast("你的体验券不足")
////                                return@let
////                            }
////                        }
////                    }
//                }
//
////                viewModel.commitOrder(
////                    list as ArrayList<ShopingBean>,
////                    this@ConfirmOrderActivity.binding.addr!!.address_id,
////                    user_coupons_id
////                )

            }
        }.show()
    }

    //支付成功的回调
    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun paySuccess(event: SuccessEvent?) {
        viewModel.check_order_pay(tradeNo)

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            0x11 -> {
                if (resultCode == RESULT_OK) {
                    data?.let {
                        val addr = it.getSerializableExtra("address") as UserAddress.Address?
                        addr?.let {
                            binding.addr = it
                        }
                    }
                }
            }
            0x12 -> {
                if (resultCode == RESULT_OK) {
                    data?.let {
                        val addr = it.getSerializableExtra("coupon") as MeCoupon.Coupons?
                        addr?.let {
                            binding.coupon = it
                            updatePrice()
                        }
                    }
                }
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

}